package com.liqi.web.controller.device;

import com.liqi.common.annotation.Log;
import com.liqi.common.constant.UserConstants;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.domain.R;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.excel.ExcelUtils;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.common.utils.uuid.GenerateCodeUtils;
import com.liqi.device.domain.DvBrand;
import com.liqi.device.domain.DvDevice;
import com.liqi.device.domain.DvModule;
import com.liqi.device.service.IDvBrandService;
import com.liqi.device.service.IDvDeviceService;
import com.liqi.device.service.IDvModuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 品牌Controller
 *
 * @author ruoyi
 * @date 2022-02-11
 */
@Api(tags = "品牌管理")
@RestController
@RequestMapping("/device/brand")
public class DvBrandController extends BaseController
{
    @Autowired
    private IDvBrandService dvBrandService;

    @Autowired
    private IDvModuleService dvModuleService;

    @Autowired
    private IDvDeviceService dvDeviceService;

    /**
     * 查询品牌列表
     */
    @PreAuthorize("@ss.hasPermi('device:brand:list')")
    @GetMapping("/list")
    public TableDataInfo list(DvBrand dvBrand)
    {
        startPage();
        List<DvBrand> list = dvBrandService.selectDvBrandList(dvBrand);
        return getDataTable(list);
    }

    /**
     * 导出品牌列表
     */
    @PreAuthorize("@ss.hasPermi('device:brand:export')")
    @Log(title = "品牌", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvBrand dvBrand)
    {
        List<DvBrand> list = dvBrandService.selectDvBrandList(dvBrand);
        ExcelUtil<DvBrand> util = new ExcelUtil<DvBrand>(DvBrand.class);
        util.exportExcel(response, list, "品牌数据");
    }

    /**
     * 获取品牌详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:brand:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dvBrandService.selectDvBrandById(id));
    }

    /**
     * 新增品牌
     */
    @PreAuthorize("@ss.hasPermi('device:brand:add')")
    @Log(title = "品牌", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DvBrand dvBrand)
    {
        dvBrand.setCode(GenerateCodeUtils.getSequnce());

        if (UserConstants.NOT_UNIQUE.equals(dvBrandService.checkCodeUnique(dvBrand)))
         {
             return AjaxResult.error("新增品牌" + dvBrand.getName() + "'失败，编码已存在");
         }
        dvBrand.setCreateBy(getUsername());
        dvBrand.setCreateTime(DateUtils.getNowDate());
        dvBrand.setUpdateBy(getUsername());
        dvBrand.setUpdateTime(DateUtils.getNowDate());
        dvBrand.setDeptId(getDeptId().toString());
        dvBrand.setCreateUserId(getUserId().toString());
    	 return toAjax(dvBrandService.insertDvBrand(dvBrand));
    }

    /**
     * 修改品牌
     */
    @PreAuthorize("@ss.hasPermi('device:brand:edit')")
    @Log(title = "品牌", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DvBrand dvBrand)
    {
    	if (UserConstants.NOT_UNIQUE.equals(dvBrandService.checkCodeUnique(dvBrand)))
        {
            return AjaxResult.error("修改品牌" + dvBrand.getName() + "'失败，编码已存在");
        }
        dvBrand.setUpdateBy(getUsername());
        dvBrand.setUpdateTime(DateUtils.getNowDate());
        return toAjax(dvBrandService.updateDvBrand(dvBrand));
    }

    /**
     * 删除品牌
     */
    @PreAuthorize("@ss.hasPermi('device:brand:remove')")
    @Log(title = "品牌", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int i = 0;
        List<DvBrand> removeDvBrand = new ArrayList<>();
        List<DvModule> unbindModules = new ArrayList<>();
        List<DvDevice> unbindDevices = new ArrayList<>();
        Map<String,List> resultMap = new HashMap<>();
        for (Long id : ids) {
            DvBrand dvBrand = dvBrandService.selectDvBrandById(id);
            DvModule module = new DvModule();
            module.setBrandCode(dvBrand.getCode());
            List<DvModule> dvModules = dvModuleService.selectDvModuleList(module);
            for (DvModule dvModule : dvModules ) {
                dvModule.setDeleteDvBrandCode(dvBrand.getCode());
                dvModule.setDeleteDvBrandName(dvBrand.getName());
                unbindModules.add(dvModule);
            }
            DvDevice dvDevice = new DvDevice();
            dvDevice.setBrandCode(dvBrand.getCode());
            List<DvDevice> dvDevices = dvDeviceService.selectDvDeviceList(dvDevice);
            for (DvDevice device : dvDevices) {
                device.setDeleteDvBrandCode(dvBrand.getCode());
                device.setDeleteDvBrandName(dvBrand.getName());
                unbindDevices.add(device);
            }
            //软删除 设置状态码为1
            dvBrand.setStatus(1);
            removeDvBrand.add(dvBrand);
        }
        if (unbindModules.size() != 0 ) {
            resultMap.put("unbindModules",unbindModules);
        }
        if (unbindDevices.size() != 0 ) {
            resultMap.put("unbindDevices",unbindDevices);
        }
        if (resultMap.size() != 0 ) {
            return AjaxResult.error("品牌已和设备以及模块绑定，需要先将设备和模块进行解绑",resultMap);
        }
        for (DvBrand dvBrand : removeDvBrand) {
            i = dvBrandService.updateDvBrand(dvBrand);
        }
        return toAjax(i);
    }


    /**
     * 获取所有有效品牌 用于下拉列表
     */
    @GetMapping("/listDropdown")
    public AjaxResult listDropdown()	{
    	DvBrand brand = new DvBrand();
    	brand.setStatus(0);//0：有效； 1：停用
        List<DvBrand> dropDownItems = dvBrandService.selectDvBrandList(brand);
        return AjaxResult.success(dropDownItems);
    }

    @ApiOperation("导入excel")
    @PostMapping("/import")
    public R importUser(@RequestPart("file") MultipartFile file) throws Exception {

        List<DvBrand> dvBrands = ExcelUtils.readMultipartFile(file, DvBrand.class);
        String message ;
        if(dvBrands.size()==0){
            return  R.ok("传入的非模板文件,请下载模板文件在进行导入");
        }
        message=   dvBrandService.importModule(dvBrands);
        if(StringUtils.isBlank(message)){
            message="上传成功！";
        }
        return R.ok(message);
    }


}
